/**
 * Orienteering Sport Diary Copyright (C) 2009 OSDiary Team
 *
 * This file is part of Orienteering Sport Diary (OSDiary).
 *
 * OSDiary is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see http://www.gnu.org/licenses/.
 */
 
package org.actions.event;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.List;
import org.data.Event;
import org.data.Race;
import org.util.DateUtil;
import org.util.EventDAO;

public class ShowEventsAction extends ActionSupport {

    private List events;
    private List nearDays;
    private int id;
    private EventWithAllRaces event;
    private Timestamp fromDate;
    private Timestamp toDate;

    private String tempFromDateString;
    private String tempToDateString;

    @Override
    public String execute() {
        Map session = ActionContext.getContext().getSession();
        Integer user_id = (Integer) session.get("id");
        if (fromDate != null && toDate != null) {
            events = EventDAO.getUserEventsBetweenDates(user_id, fromDate, toDate);
        } else if (fromDate != null && toDate == null) {
            events = EventDAO.getUserEventsBiggerEqualDate(user_id, fromDate);
        } else if (fromDate == null && toDate != null) {
            events = EventDAO.getUserEventsSmallerEqualDate(user_id, toDate);
        } else {
            events = EventDAO.getUserEvents(user_id);
        }
        session.remove("selectedPage");
        session.put("selectedPage", "showEvents");
        return SUCCESS;
    }

    public String findNearEvents() {
        Map session = ActionContext.getContext().getSession();
        Calendar firstDateCal = new GregorianCalendar();
        firstDateCal.add(Calendar.DAY_OF_MONTH, -3);
        Calendar lastDateCal = new GregorianCalendar();
        lastDateCal.add(Calendar.DAY_OF_MONTH, 3);
        Timestamp firstDate = new Timestamp(firstDateCal.getTimeInMillis());
        Timestamp lastDate = new Timestamp(lastDateCal.getTimeInMillis());
        List nearEvents = EventDAO.getUserEventsBetweenDates((Integer) session.get("id"), firstDate, lastDate);
        Calendar currentDay = firstDateCal;
        currentDay.set(Calendar.HOUR_OF_DAY, 0);
        currentDay.set(Calendar.MINUTE, 0);
        currentDay.set(Calendar.MILLISECOND, 0);
        nearDays = new ArrayList();
        for (int i = -3; i <= 3; i++) {
            DayOfEvents dayOfEvents = new DayOfEvents();
            dayOfEvents.day = (Calendar) currentDay.clone();
            List currentEvents = new ArrayList<Event>();
            Timestamp currentDateTSLeft = new Timestamp(currentDay.getTimeInMillis());
            currentDay.add(Calendar.DAY_OF_MONTH, 1);
            Timestamp currentDateTSRight = new Timestamp(currentDay.getTimeInMillis());
            for (Object o : nearEvents) {
                Event e = (Event) o;
                if (e.date.after(currentDateTSLeft) && e.date.before(currentDateTSRight)) {
                    currentEvents.add(e);
                }
            }

            dayOfEvents.events = currentEvents;

            nearDays.add(dayOfEvents);
        }
        return SUCCESS;
    }

    public List getNearDays() {
        return nearDays;
    }

    public List getEvents() {
        return this.events;
    }

    public String showEvent() {
        Map session = ActionContext.getContext().getSession();
        Event pureEvent = EventDAO.getUserEventById((Integer) session.get("id"), id);
        if (pureEvent != null) {
            event = new EventWithAllRaces(pureEvent, EventDAO.getAllRacesByEventId(id));
            return SUCCESS;
        }
        return ERROR;
    }

    public void setEventId(int id) {
        this.id = id;
    }

    public void setFromDateString(String fromDateString) {
        if (null != fromDateString || !"".equals(fromDateString)) {
            tempFromDateString = fromDateString;
            int idx = tempFromDateString.indexOf("T");
            tempFromDateString = tempFromDateString.substring(0, idx);
        } else {
            tempFromDateString = null;
        }
    }

    public void setFromTimeString(String fromTimeString) {
        if (null != tempFromDateString || null != fromTimeString || !"".equals(fromTimeString)) {
            int idx = fromTimeString.indexOf("T");
            fromTimeString = fromTimeString.substring(idx, fromTimeString.length());
            fromDate = new Timestamp(DateUtil.parseRFC(tempFromDateString  + fromTimeString));
        } else {
            fromDate = null;
        }
    }

    public void setToDateString(String toDateString) {
        if (null != toDateString || !"".equals(toDateString)) {
            tempToDateString = toDateString;
            int idx = tempToDateString.indexOf("T");
            tempToDateString = tempToDateString.substring(0, idx);
        } else {
            tempToDateString = null;
        }
    }

    public void setToTimeString(String toTimeString) {
        if (null != tempToDateString || null != toTimeString || !"".equals(toTimeString)) {
            int idx = toTimeString.indexOf("T");
            toTimeString = toTimeString.substring(idx, toTimeString.length());
            toDate = new Timestamp(DateUtil.parseRFC(tempToDateString  + toTimeString));
        } else {
            toDate = null;
        }
    }

    /**
     * @return the event
     */
    public EventWithAllRaces getEvent() {
        return event;
    }

    public class DayOfEvents {

        public List<Event> events;
        public Calendar day;

        public String getDay() {
            SimpleDateFormat df = new SimpleDateFormat(DateUtil.DATE_DISPLAY_FORMAT);
            return df.format(day.getTime());
        }
    }

    public class EventWithAllRaces {

        private List<Race> races;
        private Event event;

        public EventWithAllRaces(Event event, List<Race> races) {
            this.races = races;
            this.event = event;
        }

        /**
         * @return the races
         */
        public List<Race> getRaces() {
            return races;
        }

        /**
         * @return the event
         */
        public Event getEvent() {
            return event;
        }
    }
}

